<template>
    <div>
        <el-page-header @back="$router.back(-1)" :content="$route.meta.title" class="headerBack"></el-page-header>
        <div class="container">
            <el-card shadow="hover" style="padding:0">
                <!-- 工具栏 -->
                <div class="search-bar">
                    <div class="left">
                        <el-form class="searchForm" ref="searchForm" :model="searchForm" :inline="true">
                            <el-form-item prop="searchKey">
                                <el-select
                                    no-data-text="暂无数据" placeholder="请选择" v-model="searchForm.searchKey" clearable @clear="handleClearSelect" size="medium">
                                    <el-option
                                        v-for="item in searchColumns"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key"
                                    ></el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item prop="searchValue">
                                <el-input placeholder="请输入关键字" v-model="searchForm.searchValue" clearable @clear="handleClearKeyword" size="medium"></el-input>
                            </el-form-item>

                            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="medium">搜索</el-button>
                            <el-button type="primary" icon="el-icon-refresh-left" @click="handleResetSearch('searchForm')" size="medium">重置</el-button>
                            <el-button type="primary" icon="el-icon-plus" @click="handleOpenDialog('create')" size="medium">添加</el-button>
                            <el-button type="danger" icon="el-icon-delete" @click="handleDelete" size="medium">删除</el-button>
                            <el-button type="danger" icon="el-icon-delete" @click="handleDialogInitPermission" size="medium">初始化权限</el-button>
                        </el-form>
                    </div>
                </div>

                <!-- 表格 -->
                <el-table
                    ref="table" size="small" empty-text="-" max-height="550"
                    element-loading-text="给我一点时间"
                    fit stripe border highlight-current-row
                    v-loading="loading"
                    :data="data"
                    :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                    @selection-change="handleSelection">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column type="index" width="55" align="center"></el-table-column>
                    
                    <el-table-column label="权限名称" prop="name" column-key="name" align="center"/>
                    <el-table-column label="权限标识" prop="permission" column-key="permission" align="center"/>

                    <el-table-column label="权限类型" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="success" size="small" v-if="scope.row.type == 1">页面</el-tag>
                            <el-tag type="danger" size="small" v-else>按钮</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" prop="sort" column-key="sort" align="center"/>
                    <el-table-column label="状态" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="success" size="small" v-if="scope.row.status === 1">正常</el-tag>
                            <el-tag type="danger" size="small" v-else>禁用</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remarks" align="center"/>
                    <el-table-column label="创建时间" prop="ctime" align="center"/>
                    <el-table-column label="更新时间" prop="utime" align="center"/>
                    
                    <el-table-column label="操作" width="180px" align="center">
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" @click="handleOpenDialog('update', scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页工具栏 -->
                <div class="pagination">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="searchForm.page"
                            :page-sizes="[10, 20, 30, 50]"
                            :page-size="searchForm.rows"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>
                </div>

                <!-- 窗口 -->
                <el-dialog
                    :title="actionTypeMap[actionType]"
                    :visible.sync="dialogVisible"
                    @close="handleDialogClose">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                        <el-form-item label="权限名称" prop="name">
                            <el-input v-model="form.name" placeholder="权限名称" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="权限标识" prop="permission">
                            <el-input v-model="form.permission" placeholder="权限标识" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="form.sort" :min="99" :max="10000" placeholder="排序"></el-input-number>
                        </el-form-item>
                        <el-form-item label="类型" prop="type">
                            <el-radio-group v-model="form.type">
                                <el-radio label="1">页面</el-radio>
                                <el-radio label="2">按钮</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio :label="1">正常</el-radio>
                                <el-radio :label="0">锁定</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="备注" prop="remarks">
                            <el-input type="textarea" :rows="2" placeholder="请输入内容" style="width: 80%;" v-model="form.remarks"></el-input>
                        </el-form-item>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>

                <!-- 窗口 -->
                <el-dialog
                    title="生成初始功能"
                    :visible.sync="dialogVisibleInitPermission"
                >
                    <el-form ref="formInitPermission" :model="formInitPermission" :rules="rules" label-width="120px">
                        
                        <el-form-item label="权限" prop="initPermission">
                            <el-checkbox-group v-model="formInitPermission.initPermission">
                                <el-checkbox label="page-页面">页面</el-checkbox>
                                <el-checkbox label="add-添加">添加</el-checkbox>
                                <el-checkbox label="update-修改">修改</el-checkbox>
                                <el-checkbox label="delete-删除">删除</el-checkbox>
                                <el-checkbox label="detail-详情">详情</el-checkbox>
                                <el-checkbox label="selectPage-查询">查询</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisibleInitPermission = false">取 消</el-button>
                        <el-button @click="submitInitPermission('formInitPermission')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage, initPermission } from "@/api/admin/syspermission"
import { mapMutations } from 'vuex'
import { parseTime } from "@/libs/utils"
import valid from "@/libs/rules"

export default {
    data() {
        return {
            actionType: 'create',
            actionTypeMap: { create: '创建', update: '编辑' },
            dialogVisible: false,
            dialogVisibleInitPermission: false,
            loading: true,
            submitLoading: false,
            total: 0,
            data: [],
            searchForm: {
                page: 1,
                limit: 10,
                searchKey: '',
                searchValue: ''
            },
            searchColumns: [],
            form: {
                sort: 99,
                type: "1",
                status: 1
            },
            rules: {
                label: [valid.required()],
                value: [valid.required()]
            },
            formInitPermission: {
                initPermission: ['page-页面', 'add-添加', 'update-修改', 'delete-删除', 'detail-详情', 'selectPage-查询']
            }
            
            /**
             * 接受父页面传参，参数如下：
             * id
             */
        }
    },
    mounted() {
        this.setSearchColumnsKey()
        this.getTableDataList()
    },
    methods: {
        ...mapMutations([
            'closeTag'
        ]),
        handleCloseTab() {
            if(this.$route.query.url) {
                this.closeTag({
                    name: 'add_permission',
                    query: { id: this.$route.query.id, url: this.$route.query.url }
                })
            } else {
                this.closeTag({
                    name: 'add_permission',
                    query: { id: this.$route.query.id }
                })
            }
        },
        handleDialogInitPermission() { // 打开窗口
            this.dialogVisibleInitPermission = true
        },
        submitInitPermission(name) { // 初始化菜单权限（页面，添加，修改，删除，详情，查询）
            if(this.$route.query.url) {
                this.submitLoading = true
                let p = []
                let prefix = this.$route.query.url.replace(RegExp("/", "g"), ':').replace(':', '')
                for(let item of this.formInitPermission.initPermission) {
                    p.push(prefix+':'+item)
                }
    
                let data = {menuId: this.$route.query.id, permissions: p}
                initPermission(data).then(res => {
                    if (this.ResultMessage(res)) {
                        this.dialogVisibleInitPermission = false
                        this.submitLoading = false
                        this.getTableDataList()
                    }
                }).catch(error => {
                    this.$Notice.error({ title: '发生错误', desc: error })
                })
            }
        },
        handleOpenDialog(type, row) { // 打开表单窗口
            this.actionType = type
            this.dialogVisible = true
            if (type === 'update') {
                this.getOne(row.id).then(res => {
                    this.form = Object.assign({}, res.data)
                })
            } else {
                this.form.id = null
            }
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
        },
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getTableDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getTableDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getTableDataList()
        },
        handleReset(name) { // 重置表单
            this.$refs[name].resetFields()
        },
        setSearchColumnsKey() { // 设置查询条件Key
            this.searchColumns = []
            for (let column of this.$refs.table.columns) {
                if (column.columnKey) {
                    this.searchColumns.push({
                        key: column.columnKey,
                        label: column.label
                    })
                }
            }
        },
        handleClearSelect() { // 清空搜索下拉框
            this.searchForm.searchKey = null
        },
        handleClearKeyword() { // 清空关键字
            this.searchForm.searchValue = null
        },
        handleSearch() { // 单条件搜索
            if (this.searchForm.searchValue.trim()) {
                let searchFormDefault = Object.assign({}, this.searchForm)
                let search = Object.assign({}, this.searchForm)
                this.searchForm[this.searchForm.searchKey] = this.searchForm.searchValue
                this.getTableDataList()
                this.searchForm = searchFormDefault //恢复条件查询默认值
            }
        },
        handleSubmit(name) { // 提交表单
            this.form = Object.assign(this.form, {menuId: this.$route.query.id})
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    if (this.actionType === 'create') {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.dialogVisible = false
                                this.handleReset('form')
                                this.getTableDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$Notice.error({ title: '发生错误', desc: error })
                        })
                    } else if (this.actionType === 'update') {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.dialogVisible = false
                                this.handleReset('form')
                                this.getTableDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$Notice.error({ title: '发生错误', desc: error })
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },

        handleDelete(row) { // 删除
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted({ idList: ids }).then(response => {
                        if (this.ResultMessage(response)) {
                            this.getTableDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

        getOne(id) { // 根据ID加载数据
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },

        getTableDataList() { // 加载列表数据
            this.searchForm.menuId = this.$route.query.id
            page(this.searchForm).then(res => {
                if (this.ResultMessage(res, false)) {
                    this.data = res.data.records
                    this.total = res.data.total
                    this.loading = false
                } else {
                    this.loading = false
                }
            }).catch(error => {
                this.loading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>